#!/usr/bin/env python
import rrd
import os
import os.path
import glob
import sys
import pickle

datadir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
outdir = 'out'

if len(sys.argv) >= 2:
  outdir = sys.argv[1]


clients = os.listdir(datadir)

if not os.path.isdir(outdir):
  os.mkdir(outdir)

graphs = {}

def protectIP(ip):
 client_name = ip.split('.')
 if True:
  client_name[0]='_'
  client_name[1]='_'
 return '.'.join(client_name)
 
def readGraphs(fn):
  f = open(fn, "rb")
  obj = pickle.load(f)
  f.close()
  return obj

def config_value(key, config):
  for c in config:
    if type(c) == list and c[0] == key:
      return c[1]
  return None

def graphRRD(client, rfile, h, td):
  source_file = rfile + '.png'
  graph_config = readGraphs(rfile+'.config')
  target_file_name = "%s_%s_%d.png" % (client, os.path.basename(rfile).replace('.rrd', ''), h)
  target_file = os.path.join(outdir, target_file_name)
  title = "%s / %s" % (protectIP(client), td)
  r = rrd.RRD(rfile)
  r.graph(h*60, graph_config, target_file, title)
  
  category = 'Unkown'
  category_config = config_value('graph_category', graph_config)
  if not category_config is None:
    category = category_config
  
  title = 'Unkown'
  title_config = config_value('graph_title', graph_config)
  if not title_config is None:
    title = title_config

  if not client in graphs:
    graphs[client] = {}
  if not category in graphs[client]:
    graphs[client][category] = {}
  if not title in graphs[client][category]:
    graphs[client][category][title] = []

  graphs[client][category][title].append(target_file_name)

for client in clients:
  rrd_files = glob.glob(os.path.join(datadir, client, '*.rrd'))
  for rfile in rrd_files:
    print rfile
    if not os.path.isfile(rfile):
	  continue
    times = {'Day':24, 'Week':168, 'Month':730, 'Year':8766}
    if len(sys.argv) > 2 and sys.argv[2] in times.keys():
     graphRRD(client, rfile, times[sys.argv[2]], sys.argv[1])
    elif len(sys.argv) > 2 and not sys.argv[2] in times.keys():
     print "time '%s' unkown, please use Day, Week, Month or Year"
     sys.exit(1)
    else:
     #defaults
     keys = ['Day', 'Week', 'Month', 'Year'] # sorted order!
     for k in keys:
      graphRRD(client, rfile, times[k], k)

#print graphs

# create some ugly index.html
f = open(os.path.join(outdir, 'index.html'), "w")
stdout = sys.stdout
sys.stdout = f


print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html><head><META HTTP-EQUIV='pragma' CONTENT='no-cache'></head><body>\n"
print "<span style='white-space:nowrap'>"

print "<h3>Overview</h3>"

print "<table border='1'>"
print "<tr><td><b>Client</b></td><td><b>Category</b></td><td><b>Graph</b></td></tr>"
for graph in graphs:
 client_name = protectIP(graph)
 print "<tr><td colspan='3'><small><a href='#client_"+client_name+"'>"+client_name+"</a></small></td></tr>"

 cats = graphs[graph].keys()
 cats.sort()
 for cat in cats:
   print "<tr><td width='60px'></td><td><small><a href='#client_"+client_name+"_cat_"+cat+"'>"+cat+"</a></small></td>"
   print "<td><small>"
   titless = []
   titles = graphs[graph][cat].keys()
   titles.sort()
   for title in titles:
     titless.append("<a href='#client_"+client_name+"_cat_"+cat+"_title_"+title+"'>"+title+"</a>")
   print ', '.join(titless)
   print "</small></td></tr>"
print "</table>"


print "<p/>"

print "<h3>Graphs</h3>"

print "<table border='1'>"
for graph in graphs:
 client_name = protectIP(graph)
 print "<tr><td colspan='4'><a href='#client_"+client_name+"' name='client_"+client_name+"'>"+client_name+"</a></td></tr>"
 cats = graphs[graph].keys()
 cats.sort()
 for cat in cats:
   print "<tr><td>&nbsp;</td><td colspan='3'><a href='#client_"+client_name+"_cat_"+cat+"' name='client_"+client_name+"_cat_"+cat+"'>"+cat+"</a></td></tr>"
   titles = graphs[graph][cat].keys()
   titles.sort()
   for title in titles:
     print "<tr><td width='60px'>&nbsp;</td><td width='60px'>&nbsp;</td><td colspan='2'><a href='#client_"+client_name+"_cat_"+cat+"_title_"+title+"' name='client_"+client_name+"_cat_"+cat+"_title_"+title+"'>"+title+"</a></td></tr>"
     print "<tr><td width='60px'>&nbsp;</td><td width='60px'>&nbsp;</td><td width='60px'>&nbsp;</td><td>"
     print "<span style='white-space:nowrap'>"
     for graphi in graphs[graph][cat][title]:
      if os.path.isfile(os.path.join(outdir, graphi)):
        print "<img src='%s' alt='%s'/>" % (graphi, graphi)
      else:
        print " {graph broken '%s' (see log for details)} "%graphi
     print "</span>"
     print "</td></tr>"
print "</table>"

print "</body></html>\n"

f.close()
sys.stdout = stdout
